{%- set static = static ?? false %}
{%- set fullWidth = fullWidth ?? true %}
{%- set cols = cols ?? [] %}
{%- set rows = rows ?? [] %}
{%- set initJs = not static and (initJs ?? true) -%}
{%- set minRows = minRows ?? null %}
{%- set maxRows = maxRows ?? null %}
{%- set staticRows = static or (staticRows ?? false) or (minRows == 1 and maxRows == 1 and rows|length == 1) %}
{%- set fixedRows = not staticRows and (minRows and minRows == maxRows and minRows == rows|length) %}

{% if not static %}
    {{ hiddenInput(name, '') }}
{% endif %}

{% macro cellClass(fullWidth, col, class) %}
    {{- (class is iterable ? class : [class])|merge([
        "#{col.type}-cell",
        col.type in ['color', 'date', 'email', 'multiline', 'number', 'singleline', 'template', 'time', 'url'] ? 'textual' : null,
        fullWidth and (col.thin ?? false) ? 'thin' : null,
        col.info is defined ? 'has-info' : null,
    ]|filter)|join(' ') -}}
{% endmacro %}

{% set tableAttributes = {
    id: id,
    class: [
        'editable',
        fullWidth ? 'fullwidth',
        static ? 'static',
        rows|length == 0 ? 'hidden',
    ]|filter,
} %}

{%- if block('attr') is defined %}
  {%- set tableAttributes = tableAttributes|merge(('<div ' ~ block('attr') ~ '>')|parseAttr, recursive=true) %}
{% endif %}

<table {{ attr(tableAttributes) }}>
    <thead>
        <tr>
            {% for col in cols %}
                {%- switch col.type %}
                    {%- case 'time' %}
                        {%- do view.registerAssetBundle('craft\\web\\assets\\timepicker\\TimepickerAsset') %}
                    {%- case 'template' %}
                        {%- do view.registerAssetBundle("craft\\web\\assets\\vue\\VueAsset") %}
                {%- endswitch %}
                <th scope="col" class="{{ _self.cellClass(fullWidth, col, col.class ?? []) }}">
                    {%- if col.headingHtml is defined %}
                        {{- col.headingHtml|raw }}
                    {%- elseif col.heading ?? false %}
                        {{- col.heading }}
                    {%- else %}
                        &nbsp;
                    {%- endif %}
                    {%- if col.info is defined -%}
                        <span class="info">{{ col.info|md|raw }}</span>
                    {%- endif -%}
                </th>
            {% endfor %}
            {% if not staticRows %}
                <th colspan="{{ fixedRows ? 1 : 2 }}"></th>
            {% endif %}
        </tr>
    </thead>
    <tbody>
        {% for rowId, row in rows %}
            <tr data-id="{{ rowId }}">
                {% for colId, col in cols %}
                    {% set cell = row[colId] is defined ? row[colId] : (defaultValues[colId] ?? null) %}
                    {% set value = cell.value is defined ? cell.value : cell %}
                    {% if col.type == 'heading' %}
                        <th scope="row" class="{{ _self.cellClass(fullWidth, col, cell.class ?? col.class ?? []) }}">{{ value|raw }}</th>
                    {% elseif col.type == 'html' %}
                        <td class="{{ _self.cellClass(fullWidth, col, cell.class ?? col.class ?? []) }}">{{ value|raw }}</td>
                    {% else %}
                        {% set hasErrors = cell.hasErrors ?? false %}
                        {% set cellName = name~'['~rowId~']['~colId~']' %}
                        {% set isCode = (col.code ?? false) or col.type == 'color' %}
                        <td class="{{ _self.cellClass(fullWidth, col, col.class ?? []) }} {% if isCode %}code{% endif %} {% if hasErrors %}error{% endif %}"{% if col.width ?? false %} width="{{ col.width }}"{% endif %}>
                            {% block tablecell %}
                                {%- switch col.type -%}
                                    {%- case 'checkbox' -%}
                                        <div class="checkbox-wrapper">
                                            {% include "_includes/forms/checkbox" with {
                                                name: cellName,
                                                value:  col.value ?? 1,
                                                checked: value is not empty,
                                                disabled: static
                                            } only %}
                                        </div>
                                    {%- case 'color' -%}
                                        {% include "_includes/forms/color" with {
                                            name: cellName,
                                            value: value,
                                            small: true,
                                            disabled: static
                                        } only %}
                                    {%- case 'date' -%}
                                        {% include "_includes/forms/date" with {
                                            name: cellName,
                                            value: value,
                                            disabled: static
                                        } only %}
                                    {%- case 'lightswitch' -%}
                                        {% include "_includes/forms/lightswitch" with {
                                            name: cellName,
                                            on: value,
                                            value: col.value ?? 1,
                                            small: true,
                                            disabled: static
                                        } only %}
                                    {% case 'select' -%}
                                        {% include "_includes/forms/select" with {
                                            class: 'small',
                                            name: cellName,
                                            options: cell.options ?? col.options,
                                            value: value,
                                            disabled: static
                                        } only %}
                                    {%- case 'time' -%}
                                        {% include "_includes/forms/time" with {
                                            name: cellName,
                                            value: value,
                                            disabled: static
                                        } only %}
                                    {%- case 'email' or 'url' -%}
                                        {% include "_includes/forms/text" with {
                                            type: col.type,
                                            name: cellName,
                                            placeholder: col.placeholder ?? null,
                                            value:  value,
                                            disabled: static
                                        } only %}
                                    {%- case 'template' -%}
                                        {% include "_includes/forms/autosuggest" with {
                                            name: cellName,
                                            suggestions: craft.cp.getTemplateSuggestions(),
                                            value: value,
                                            disabled: static
                                        } only %}
                                    {%- default -%}
                                        {% if static %}
                                            <pre class="disabled">{{ value }}</pre>
                                        {% else %}
                                            <textarea name="{{ cellName }}" rows="{{ col.rows ?? 1 }}"{% if col.placeholder is defined %} placeholder="{{ col.placeholder }}"{% endif %}>{{ value }}</textarea>
                                        {% endif %}
                                {%- endswitch -%}
                            {% endblock %}
                        </td>
                    {% endif %}
                {% endfor %}
                {% if not staticRows %}
                    <td class="thin action"><a class="move icon" title="{{ 'Reorder'|t('app') }}" aria-label="{{ 'Reorder'|t('app') }}"></a></td>
                    {% if not fixedRows %}<td class="thin action"><a class="delete icon" title="{{ 'Delete'|t('app') }}" aria-label="{{ 'Delete'|t('app') }}"></a></td>{% endif %}
                {% endif %}
            </tr>
        {% endfor %}
    </tbody>
</table>
{% if not staticRows and not fixedRows %}
    <button type="button" class="btn add icon">{{ addRowLabel ?? "Add a row"|t('app') }}</button>
{% endif %}

{% if initJs %}
    {% set jsId = id|namespaceInputId|e('js') %}
    {% set jsName = name|namespaceInputName|e('js') %}
    {% set jsCols = cols|json_encode %}
    {% set defaultValues = defaultValues ?? null %}
    {% js %}
        new Craft.EditableTable("{{ jsId }}", "{{ jsName }}", {{ jsCols|raw }}, {
            defaultValues: {{ defaultValues ? defaultValues|json_encode|raw : '{}' }},
            staticRows: {{ staticRows ? 'true' : 'false' }},
            minRows: {{ minRows ? minRows : 'null' }},
            maxRows: {{ maxRows ? maxRows : 'null' }}
        });
    {% endjs %}
{% endif %}
